package com.hup.sokoban.service.common;

import com.hup.utils.commons.exception.AppExceptionHandler;
import com.hup.utils.commons.exception.ErrInfo;
import com.hup.utils.io.audio.AudioInfo;
import com.hup.utils.io.audio.AudioPlayTask.TaskListener;
import com.hup.utils.io.audio.ClipPlayTask;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hugan
 * @date 2020/5/27
 */
@Log4j2
@Component
public class AudioService {

    private final ClipPlayTask audioWinning;
    private final ClipPlayTask audioMove;
    /**
     * 加载异常
     */
    @Getter
    private final List<String> loadErr;
    /**
     * 静音
     */
    @Getter
    @Setter
    private boolean mute;

    public AudioService() {
        ArrayList<String> err = new ArrayList<>();//下面是单线程访问的
        audioWinning = new ClipPlayTask("/audio/ff7-AGreatSuccess.wav", new TaskListener<ClipPlayTask>() {
            @Override
            public void onGetInfo(AudioInfo audioInfo, Exception e, ClipPlayTask task) {
                if (audioInfo != null) {
                    task.getMasterGain().setValue(-5);
                    task.setLoop(true);
                } else {
                    ErrInfo errInfo = AppExceptionHandler.handle("通关音效加载错误:", e);
                    err.add(errInfo.getErrMsg());
                }
            }
        });
        audioMove = new ClipPlayTask("/audio/mota-move.wav", new TaskListener<ClipPlayTask>() {
            @Override
            public void onGetInfo(AudioInfo audioInfo, Exception e, ClipPlayTask task) {
                if (audioInfo != null) {
                    task.getMasterGain().setValue(-5);
                } else {
                    ErrInfo errInfo = AppExceptionHandler.handle("移动音效加载错误:", e);
                    err.add(errInfo.getErrMsg());
                }
            }
        });
        loadErr = err.isEmpty() ? null : err;
    }

    public void playWinning() {
        if (mute) return;
        audioWinning.play();
    }

    public void stopWinning() {
        if (mute) return;
        audioWinning.stop();
    }

    public void move() {
        if (mute) return;
        audioMove.play();
    }

}
